﻿using AntDesign;
using Microsoft.AspNetCore.Components;

namespace Blazor.Core.Extensions;

public static class ModalServiceExtensions
{
    private static RenderFragment Icon = builder =>
    {
        builder.OpenComponent(0, typeof(Icon));
        builder.AddAttribute(1, "Type", IconType.Outline.ExclamationCircle);
        builder.CloseComponent();
    };
    
    public static async Task<bool> WhenConfirm(this ModalService modalService, string title, string content)
    {
        var tcs = new TaskCompletionSource<bool>();
        modalService.Confirm(new ConfirmOptions()
        {
            Title = title,
            Content = content,
            OnOk = _ =>
            {
                tcs.SetResult(true);
                return Task.CompletedTask;
            },
            OnCancel = _ =>
            {
                tcs.SetResult(false);
                return Task.CompletedTask;
            }
        });
        
        return await tcs.Task;
    }
    
    public static async Task<bool> WhenConfirm(this ModalService modalService, string title, string content, Func<ModalClosingEventArgs, Task<bool>> onOk)
    {
        var tcs = new TaskCompletionSource<bool>();
        modalService.Confirm(new ConfirmOptions()
        {
            Title = title,
            Icon = Icon,
            Content = content,
            OnOk = async e =>
            {
                var success = await onOk.Invoke(e);
                if (success)
                {
                    tcs.SetResult(true);
                }
                else
                {
                    e.Reject();
                }
            },
            OnCancel = _ =>
            {
                tcs.SetResult(false);
                return Task.CompletedTask;
            }
        });
        
        return await tcs.Task;
    }

    public static async Task<TResult?> OpenCustomModal<TModal, TParam, TResult>(this ModalService modalService,
        TParam param) where TModal : FeedbackComponent<TParam, TResult>
    {
        var tcs = new TaskCompletionSource<TResult?>();

        var r = await modalService.CreateConfirmAsync<TModal, TParam, TResult?>(new ConfirmOptions()
        {
            Width = 800,
        }, param);
        var callback = (TResult? result) =>
        {
            tcs.SetResult(result);
            return Task.CompletedTask;
        };

        r.OnOk = callback;
        r.OnCancel = callback;

        return await tcs.Task;
    }
}